package com.hands.sample.handlers;

import com.amazon.ask.dispatcher.request.handler.HandlerInput;
import com.amazon.ask.dispatcher.request.handler.impl.CanFulfillIntentRequestHandler;
import com.amazon.ask.model.Response;
import com.amazon.ask.model.Slot;
import com.amazon.ask.model.canfulfill.*;
import com.hands.commen.utils.time.TimeNormalizer;
import com.hands.commen.utils.time.TimeUnit;
import com.hands.sample.service.impl.InstructionsInfoServiceImpl;
import com.hands.sample.service.impl.WisdomHomeService;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.util.Optional;
import static com.amazon.ask.request.Predicates.canFulfillIntentName;
import static com.amazon.ask.request.Predicates.intentName;

public class CommonHandler implements CanFulfillIntentRequestHandler {

    private static final Logger logger = LoggerFactory.getLogger(CommonHandler.class);

    @Override
    public boolean canHandle(HandlerInput handlerInput, CanFulfillIntentRequest canFulfillIntentRequest) {
        String requestIntentName = canFulfillIntentRequest.getIntent().getName();
        ///判断是否存在技能 （false：不存在,true：存在）
        boolean istrue =  handlerInput.matches(canFulfillIntentName(requestIntentName));
        return istrue;
    }

    @Override
    public Optional<Response> handle(HandlerInput handlerInput, CanFulfillIntentRequest canFulfillIntentRequest) {
        CanFulfillSlot CanUnderstand ;
        CanFulfillIntent canFulfillIntent=null;
        try {
            Slot slot = canFulfillIntentRequest.getIntent().getSlots().get("SlotName");
            String v = slot.getValue();
            JSONObject objV = JSONObject.fromObject(v);
            String answer="";
            if (objV.get("answer")!=null)
                answer = objV.get("answer").toString();
            String domainArea = canFulfillIntentRequest.getIntent().getName();
            String speekstr = objV.get("query").toString().trim();
            ///蓝牙特殊处理
            if (speekstr.indexOf("打开蓝牙")>-1||speekstr.indexOf("关闭蓝牙")>-1)
            {
                CanUnderstand = CanFulfillSlot.builder().withCanUnderstand(CanUnderstandSlotValues.NO).withCanFulfill(CanFulfillSlotValues.NO).build();
                canFulfillIntent = CanFulfillIntent.builder().withCanFulfill(CanFulfillIntentValues.NO).putSlotsItem("slotName1", CanUnderstand).build();
                return handlerInput.getResponseBuilder().withCanFulfillIntent(canFulfillIntent).build();
            }
            JSONObject speek=new JSONObject();
            speek.put("query",speekstr);
            speek.put("realm",domainArea);

            //SocketClient.sendtts("0760c53ba14374872777f3c1529f389f","欢迎光临智慧体验屋");
            URL url = TimeNormalizer.class.getResource("/TimeExp.m");
            System.out.println(url.toURI().toString());
            TimeNormalizer normalizer = new TimeNormalizer(url.toURI().toString());
            normalizer.setPreferFuture(true);
            normalizer.parse(objV.get("query").toString().trim());
            TimeUnit[] unit = normalizer.getTimeUnit();

            if (unit.length>0)
                speek.put("fromtime", ""+unit[0].getTime().getTime());

            if (unit.length>1)
                speek.put("lasttime",""+unit[1].getTime().getTime());


            JSONObject returnMsg = WisdomHomeService.requestSound(handlerInput, speek.toString());


            canFulfillIntent = WisdomHomeService.responeCanFulfillSlot(returnMsg, speek.toString(),domainArea,answer,handlerInput);

            //logC.writeFile("","结束CanFulfillIntentRequest时间："+logC.getCurrentYYYYMMDDHHMMSS()+"\r\n");
            //判断返回结果，并根据音响回传协议进行设置返回值
            //CanFulfillIntent canFulfillIntent = WisdomHomeService.responeCanFulfillSlot(returnMsg, speek,area,handlerInput);
            return handlerInput.getResponseBuilder()
                    .withCanFulfillIntent(canFulfillIntent).build();
        }catch (Exception ex){
           // logC.writeFile("",ex.toString());
            CanUnderstand = CanFulfillSlot.builder().withCanUnderstand(CanUnderstandSlotValues.NO).withCanFulfill(CanFulfillSlotValues.NO).build();
            canFulfillIntent = CanFulfillIntent.builder().withCanFulfill(CanFulfillIntentValues.NO).putSlotsItem("slotName1", CanUnderstand).build();
        }
        return handlerInput.getResponseBuilder()
                .build();
    }
}
